<?php

namespace app\api\Service;

use app\common\library\Auth;
use app\common\library\Ems;
use app\common\library\Sms;
use think\Db;
use fast\Random;
use think\Config;
use think\Validate;
use think\Response;

class UserService
{

    // 获取个人信息
    public static function getUserInfo($data)
    {
        $auth = Auth::instance();
        $userInfo = $auth->getUserinfo();
        $userInfo['bio'] = $auth->bio;
        $exist = \app\admin\model\Steward::where(['user_id'=>$userInfo['id']])->value('id');
        if($exist) {
            $userInfo['is_steward'] = 1;
        }else {
            $userInfo['is_steward'] = 0;
        }
        return ['code'=>1,'msg'=>'获取成功','data'=>$userInfo];
    }

    // 账号密码注册
    public static function register($data)
    {
        $auth = Auth::instance();
        $mobile = $data['mobile'];
        $code = $data['code'];
        $password = $data['password'];
        $confirmpw = $data['confirmpw'];

        if(isset($data['invite']) && $data['invite']){
            $invite = $data['invite'];
            $firstChar = substr($invite, 0, 1);
            if($firstChar == 'U'){
                $pid = substr($invite, 1);
                $parent = \app\admin\model\User::get($pid);
                if(!$parent) return ['code'=>0,'msg'=>'邀请码不正确','data'=>''];
            }
            if($firstChar == 'S'){
                $pid = 0;
            }
        }else{
            $pid = 0;
        }

        $username = $mobile;
        if (!$username || !$password) {
            return ['code'=>0,'msg'=>'无效参数','data'=>''];
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            return ['code'=>0,'msg'=>'手机号格式不正确','data'=>''];
        }
        $ret = Sms::check($mobile, $code, 'register');
//        $ret = true;
        if (!$ret) {
            return ['code'=>0,'msg'=>'验证码错误','data'=>''];
        }
        if ($password != $confirmpw) {
            return ['code'=>0,'msg'=>'两次密码不一致','data'=>''];
        }

        $ret = $auth->register($mobile, $password, '', $mobile, ['pid'=>$pid]);
        if ($ret) {

            // 判断pid是否不为0
            if( isset($pid) && $pid) {

                // 邀请人奖励优惠券
                $res = userInviteReward($pid);
//                    return $res;
            }

            Sms::flush($mobile, 'register');
            $data = $auth->getUserinfo();
            if(isset($invite)) $data['invite'] = $invite;
            return ['code'=>1,'msg'=>'注册成功','data'=>$data];
        } else {
            return ['code'=>0,'msg'=>$auth->getError(),'data'=>''];
        }
    }

    // 账号密码登录
    public static function login($data)
    {
        $auth = Auth::instance();
        $account = $data['mobile'];
        $password = $data['password'];
        if (!$account || !$password) {
            return ['code'=>0,'msg'=>'无效参数','data'=>''];
        }
        $ret = $auth->login($account, $password);
        if ($ret) {
            $data = $auth->getUserinfo();
            return ['code'=>1,'msg'=>'登录成功','data'=>$data];
        } else {
            return ['code'=>0,'msg'=>$auth->getError(),'data'=>''];
        }
    }

    // 验证码登录
    public static function mobilelogin($data)
    {
        $auth = Auth::instance();
        $mobile = $data['mobile'];
        $captcha = $data['code'];

        if (!$mobile || !$captcha) {
            return ['code'=>0,'msg'=>'无效参数','data'=>''];
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            return ['code'=>0,'msg'=>'手机号格式不正确','data'=>''];
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            return ['code'=>0,'msg'=>'验证码错误','data'=>''];
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status == 'hidden') {
                return ['code'=>0,'msg'=>'账号已锁定','data'=>''];
            }
            if ($user->status == 'logoff') {
                return ['code'=>0,'msg'=>'账号已注销','data'=>''];
            }
            //如果已经有账号则直接登录
            $ret = $auth->direct($user->id);
        } else {
            $ret = $auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = $auth->getUserinfo();
            return ['code'=>1,'msg'=>'登录成功','data'=>$data];
        } else {
            return ['code'=>0,'msg'=>$auth->getError(),'data'=>''];
        }
    }

    // 修改个人信息
    public static function editUserProfile($data)
    {
        $auth = Auth::instance();
        $user = $auth->getUser();
        $nickname = $data['nickname'];
        $bio = $data['bio'];
        $avatar = $data['avatar'];

        if ($nickname) $user->nickname = $nickname;
        if ($bio) $user->bio = $bio;
        if ($avatar) $user->avatar = $avatar;
        if(!$nickname && !$bio && !$avatar) return ['code'=>0,'msg'=>'没有更新任何数据','data'=>''];
        $user->save();
        return ['code'=>1,'msg'=>'操作成功','data'=>''];
    }

    // 重置密码
    public static function resetpwd($data)
    {
//
        $mobile = $data['mobile'];
        $newpassword = $data['password'];
        $confirmpw = $data['confirmpw'];
        $captcha = $data['code'];
        if (!$newpassword || !$captcha) {
            return ['code'=>0,'msg'=>'无效参数','data'=>''];
        }

        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            return ['code'=>0,'msg'=>'密码必须为6到30个字符','data'=>''];
        }
        if ($newpassword != $confirmpw) {
            return ['code'=>0,'msg'=>'两次密码不一致','data'=>''];
        }

        if (!Validate::regex($mobile, "^1\d{10}$")) {
            return ['code'=>0,'msg'=>'手机号格式不正确','data'=>''];
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            return ['code'=>0,'msg'=>'用户信息不存在','data'=>''];
        }
        $status = $user->status;
        if ($status == 'hidden') {
            return ['code'=>0,'msg'=>'账号已锁定','data'=>''];
        }
        if($status == 'logoff'){
            return ['code'=>0,'msg'=>'账号已注销','data'=>''];
        }
        $ret = Sms::check($mobile, $captcha, 'resetpwd');
//        $ret = true;
        if (!$ret) {
            return ['code'=>0,'msg'=>'验证码错误','data'=>''];
        }
        Sms::flush($mobile, 'resetpwd');
        //模拟一次登录
//        $auth = Auth::instance();
//        $auth->direct($user->id);

        $salt = Random::alnum();
        $user->password = md5(md5($newpassword) . $salt);
        $ret = $user->save(['loginfailure' => 0, 'password' => $user->password, 'salt' => $salt]);
        if ($ret) {
            return ['code'=>1,'msg'=>'操作成功','data'=>['password' => $user->password, 'salt' => $salt]];
        } else {
            return ['code'=>1,'msg'=>'操作失败','data'=>''];
        }
    }

    // 获取我的分享
    public static function getUserShare($data)
    {
        $auth = Auth::instance();

        $params['text'] = request()->domain() . "/h5?code=U{$auth->id}&type=0";

        $qrCode = \addons\qrcode\library\Service::qrcode($params);

        $mimetype = 'png' == 'png' ? 'image/png' : 'image/svg+xml';

        $response = Response::create()->header("Content-Type", $mimetype);

        // 直接显示二维码
        header('Content-Type: ' . $qrCode->getContentType());
        $response->content($qrCode->writeString());

        // 写入到文件

        $qrcodePath = ROOT_PATH . 'public/share/user/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }
        if (is_really_writable($qrcodePath)) {
            $filePath = $qrcodePath . md5($auth->id) . '.png';
            $qrCode->writeFile($filePath);
        }
        $url = request()->domain() . '/share/user/' . md5($auth->id) . '.png';

        // 邀请人数
        $count = Db::name('user')->where('pid', $auth->id)->count();

        return ['code'=>1,'msg'=>'获取成功','data'=>['url'=>$url, 'count'=>$count]];
    }

    // 获取分享详情
    public static function getShareDetails($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $limit = isset($data['limit']) ? $data['limit'] : 10;
        $list = Db::name('user')->where('pid', $user_id)->order('createtime desc')->field('id')
            ->paginate($limit)
            ->each(
            function($item){
                $userInfo = \app\admin\model\User::where(['id'=>$item['id']])->field('nickname,avatar,createtime')
                    ->find();
                if($userInfo) {
                    $item['nickname'] = $userInfo['nickname'];
                    $item['avatar'] = $userInfo['avatar'];
                    $item['createtime_text'] = date('Y-m-d H:i:s', $userInfo['createtime']);
                }
                return $item;
            }
        );
        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }

    // 注销账号
    public static function logoff()
    {
        $auth = Auth::instance();
        $user = $auth->getUser();
        $user->status = 'logoff';
        // 修改状态
        $user->save();
        // 退出登录
        $auth->logout();
        return ['code'=>1,'msg'=>'注销成功','data'=>''];
    }

    // 退出登录
    public static function logout()
    {
        $auth = Auth::instance();
        $auth->logout();
        return ['code'=>1,'msg'=>'退出成功','data'=>''];
    }

    // 意见反馈
    public static function Feedback($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $content = $data['content'];
        $images = $data['images'];
        if (!$content) {
            return ['code'=>0,'msg'=>'反馈内容不能为空','data'=>''];
        }

        try{
            $params = [
                'user_id'       => $user_id,
                'content'       => $content,
                'images'        => $images,
            ];

            $result = \app\admin\model\Feedback::create($params);

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }

        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }
}